package com.ylzinfo.ms.fetchdemo;

import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.Select;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @Description:
 * @Product: IntelliJ IDEA
 * @Author Rogchen rogchen128@gmail.com
 * @Created Date: 20-2-11 17:47
 **/
public class chrome测试 {

    String url = "https://ssc.mohrss.gov.cn/cardInfo/PagePlague/pagePlagueList";

    @Test
    public void testSelenium() throws IOException {
        System.setProperty("webdriver.chrome.driver", "/media/chenhk/working/projects/maven/fetch-demo/chromedriver");// chromedriver服务地址
        WebDriver driver = new ChromeDriver(); // 新建一个WebDriver 的对象，但是new 的是谷歌的驱动
        String url = "https://ssc.mohrss.gov.cn/main?_api_timestamp=1580909751215&security=VxYGjhhH1yTAm7OgefOywfWQ27nVlhiV8t8a3fQdWgSwh6xcJw1BfT0aE%2BjyXQXuiENOjW%2Bgp89zicigqxzUlTvwh44xeQSPzwNT8poORIbzJFl4cTRv7wjMaZtiH60WAYgzHE7m1R%2Foo6AMnhwTYva0yNa4HkRXGsd6FglBINgEHsAsotPDd0d2diVfRBjBYRgOTEQzJVBLcMMIHqMhYA%3D%3D&_api_name=get_token&api_access_key=15dfa422d02d49108741f011b6a5e3f9&_api_signature=iteFyLXHfdIzy6639R%2FmZ%2FsQHfc%3D&return_url=http%3A%2F%2Fwww.ylzinfo.com&_api_version=1.0.0&_api_access_key=15dfa422d02d49108741f011b6a5e3f9";
//        String url = "http://www.baidu.com";
        //驱动的网址
        driver.get(url);
        try {
            driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
        } catch (Exception e) {
            e.printStackTrace();
        }
//        //浏览器窗口变大
//        driver.manage().window().maximize();
//        如果有弹窗 就关闭
        //定位遮照层
        WebElement altBtn = driver.findElement(By.className("m-guide"));
        try {
//            线程睡眠2秒等待 页面加载完成
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if (StringUtils.isEmpty(altBtn.getAttribute("style")) && !altBtn.getAttribute("style").contains("none")) {
//            寻找关闭按钮
            WebElement svgBtn = altBtn.findElement(By.tagName("svg"));
            svgBtn.click();
        }
//地一个页面
//        查找轮播图  特别就在于图片，其他无法定位到  https://ssc.mohrss.gov.cn/dist/assets/images/app_banner2_icon.c6f491.png
        String imgurl = "/dist/assets/images/app_banner2_icon.c6f491.png";
        WebElement lbt = ((ChromeDriver) driver).findElementByClassName("vux-swiper");
        List<WebElement> list = lbt.findElements(By.className("vux-swiper-item"));
        for (WebElement lbt1 : list) {
            WebElement lbt2 = lbt1.findElement(By.tagName("a"));
            WebElement lbt3 = lbt2.findElement(By.className("vux-img"));
            if (lbt3.getAttribute("style").contains(imgurl)) {
//                点击跳转到疫情专区去
                lbt2.click();
                break;
            }
        }
//        第二个页面跳转
        try {
            driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
        } catch (Exception e) {
            e.printStackTrace();
        }
        WebElement rsxg = driver.findElement(By.className("plague-content_policy"));
        rsxg.click();
////        第三个页面
//        try {
//            driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        WebElement threePage = driver.findElement(By.cssSelector("div.sub-view_content>div.page-plague>div.sub-view_content"));
//        WebElement threePage_tab = threePage.findElement(By.className("tab-item_all"));
//        threePage_tab.findElement(By.cssSelector("div:nth-child(1)")).click();
////        临时设置文本存储
//        File file = new File("/home/chenhk/tool", "pachong");
//        PrintWriter printWriter = new PrintWriter(new FileWriter(file, true), true);//第二个参数为true，从文件末尾写入 为false则从开头写入
////      循环获取内容输出到文本中去
//        List<WebElement> contents = threePage.findElements(By.cssSelector("div.app-plague_content>div.app-plague_list"));
//        for (WebElement web : contents) {
//            try {
//                driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//            web.click();
//            try {
//                driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
////          第四个页面 div#app>div>div>div>div.sub-view_content
//            WebElement fourPage = driver.findElement(By.cssSelector("div.sub-view_content>div.page-plague>div.sub-view_content>div.sub-view_content>div.app-plague_details"));
//            WebElement fourPage_title = fourPage.findElement(By.className("plague-details_title"));
//            String title = fourPage_title.getText();
//            System.out.println(title);
//            WebElement fourPage_content = fourPage.findElement(By.className("plague-details_text"));
//            String conthtml = fourPage_content.getAttribute("innerHTML");
//            System.out.println(conthtml);
//            String newConthHtml = null;
//            if (!conthtml.contains("https")) {
//                newConthHtml = conthtml.replace("src=\"//", "src=\"https://");
//                System.out.println(newConthHtml);
//            }
//            printWriter.println(title + "                   " + newConthHtml);
//            driver.navigate().back();
//        }
//        printWriter.close();//记得关闭输入流
//
////        //定位输入框元素
//        WebElement txtbox = driver.findElement(By.name("wd"));
////
////        //在输入框输入文本
//        txtbox.sendKeys("HelloWorld");
////
////        //定位按钮元素
//        WebElement btn = driver.findElement(By.id("su"));
////
////        //点击按钮
//        btn.click();
//
//        Document document = Jsoup.parse(driver.getPageSource());
//        System.out.println(document.body());
        //关闭驱动
        driver.close();
//        关闭浏览器
        driver.quit();
    }

    @Test
    public void 多次页面点击() throws IOException {
        System.setProperty("webdriver.chrome.driver", "/media/chenhk/working/projects/maven/fetch-demo/chromedriver");// chromedriver服务地址
//        不打开浏览器
        ChromeOptions options = new ChromeOptions();
//        options.addArguments("headless");
        WebDriver driver = new ChromeDriver(options); // 新建一个WebDriver 的对象，但是new 的是谷歌的驱动
        String url = "https://ssc.mohrss.gov.cn/main?_api_timestamp=1580909751215&security=VxYGjhhH1yTAm7OgefOywfWQ27nVlhiV8t8a3fQdWgSwh6xcJw1BfT0aE%2BjyXQXuiENOjW%2Bgp89zicigqxzUlTvwh44xeQSPzwNT8poORIbzJFl4cTRv7wjMaZtiH60WAYgzHE7m1R%2Foo6AMnhwTYva0yNa4HkRXGsd6FglBINgEHsAsotPDd0d2diVfRBjBYRgOTEQzJVBLcMMIHqMhYA%3D%3D&_api_name=get_token&api_access_key=15dfa422d02d49108741f011b6a5e3f9&_api_signature=iteFyLXHfdIzy6639R%2FmZ%2FsQHfc%3D&return_url=http%3A%2F%2Fwww.ylzinfo.com&_api_version=1.0.0&_api_access_key=15dfa422d02d49108741f011b6a5e3f9";
//        String url = "http://www.baidu.com";
        //驱动的网址
        driver.get(url);
        try {
            driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
        } catch (Exception e) {
            e.printStackTrace();
        }
//        //浏览器窗口变大
//        driver.manage().window().maximize();

        try {
//            线程睡眠2秒等待 页面加载完成
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
//        如果有弹窗 就关闭
        //定位遮照层
        WebElement altBtn = driver.findElement(By.className("m-guide"));
//        if (StringUtils.isEmpty(altBtn.getAttribute("style")) && !altBtn.getAttribute("style").contains("none")) {
////            寻找关闭按钮
//            WebElement svgBtn = altBtn.findElement(By.tagName("svg"));
//            svgBtn.click();
//        }
//        直接跳转到要抓取的页面
        driver.get("https://ssc.mohrss.gov.cn/cardInfo/PagePlague/pagePlagueList");
//        第三个页面
        try {
            driver.manage().timeouts().implicitlyWait(25, TimeUnit.SECONDS);
        } catch (Exception e) {
            e.printStackTrace();
        }
        WebElement threePage = driver.findElement(By.cssSelector("div.sub-view_content>div.page-plague>div.sub-view_content"));
        WebElement threePage_tab = threePage.findElement(By.className("tab-item_all"));
//      todo 循环获取内容输出到文本中去
//        List<WebElement> contents = threePage.findElements(By.cssSelector("div.app-plague_content>div:nth-child(1)>div.plague-list_item"));
//        getListInfo(driver, contents);
        //        默认地一个，所以不模拟点击了---> 地市栏目
        threePage_tab.findElement(By.cssSelector("div:nth-child(2)")).click();
        try {
//            线程睡眠2秒等待 页面加载完成
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        try {
            driver.manage().timeouts().implicitlyWait(25, TimeUnit.SECONDS);
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<WebElement> threePage_pro = threePage.findElements(By.cssSelector("div.app-plague_tab_local>div.province-list_block>div.province-list_item"));
        for (WebElement pro : threePage_pro) {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
                break;
            }
            //        选择地市
            threePage.findElement(By.cssSelector("div.plague-content_province>div.content-province_selected")).click();

            //移动到窗口绝对位置坐标，如下移动到纵坐标20像素位置
//            ((JavascriptExecutor) driver).executeScript("window.scrollTo(0, 1000)");
            //将滚动条滚动至第三篇文章列表位置
            ((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", pro);
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
                break;
            }
            pro.click();
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
                break;
            }
            System.out.println("输出地址：->"+pro.getAttribute("innerText"));
            try {
                driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
            } catch (Exception e) {
                e.printStackTrace();
                break;
            }
            List<WebElement> difang_contents = threePage.findElements(By.cssSelector("div.app-plague_content>div:nth-child(2)>div.plague-list_item"));
//        写入地方
            getListInfo(driver, difang_contents);

        }
        driver.close();
//        关闭浏览器
        driver.quit();
    }

    private void getListInfo(WebDriver driver, List<WebElement> contents) {
//        临时设置文本存储
        File file = new File("/home/chenhk/tool", "pachong");
        PrintWriter printWriter = null;//第二个参数为true，从文件末尾写入 为false则从开头写入
        try {
            printWriter = new PrintWriter(new FileWriter(file, true), true);
        } catch (IOException e) {
            e.printStackTrace();
        }
        WebElement fourPage, fourPage_title, fourPage_content = null;
        for (WebElement web : contents) {
//            获取抓取的的时间
            String pubTime = web.findElement(By.cssSelector("div.list-item_info>p")).getText();
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
                break;
            }
            web.click();
            try {
                driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
            } catch (Exception e) {
                e.printStackTrace();
                break;
            }
//          第四个页面 div#app>div>div>div>div.sub-view_content
            fourPage = driver.findElement(By.cssSelector("div.sub-view_content>div.page-plague>div.sub-view_content>div.sub-view_content>div.app-plague_details"));
            fourPage_title = fourPage.findElement(By.className("plague-details_title"));
            String title = fourPage_title.getText();
            System.out.println(title);
            fourPage_content = fourPage.findElement(By.className("plague-details_text"));
            String conthtml = fourPage_content.getAttribute("innerHTML");
            System.out.println(conthtml);
            String newConthHtml = null;
            if (!conthtml.contains("https")) {
                newConthHtml = conthtml.replace("src=\"//", "src=\"https://");
                System.out.println(newConthHtml);
            }
            printWriter.println(title + "                   发布时间：" + pubTime.replace("发布日期: ", "") + "   发布内容：" + newConthHtml + "\n\t");
            driver.navigate().back();
        }
        printWriter.close();//记得关闭输入流
    }

    public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver", "/media/chenhk/working/projects/maven/fetch-demo/chromedriver");// chromedriver服务地址
        WebDriver driver = new ChromeDriver(); // 新建一个WebDriver 的对象，但是new 的是谷歌的驱动
        String url = "https://ssc.mohrss.gov.cn/main?_api_timestamp=1580909751215&security=VxYGjhhH1yTAm7OgefOywfWQ27nVlhiV8t8a3fQdWgSwh6xcJw1BfT0aE%2BjyXQXuiENOjW%2Bgp89zicigqxzUlTvwh44xeQSPzwNT8poORIbzJFl4cTRv7wjMaZtiH60WAYgzHE7m1R%2Foo6AMnhwTYva0yNa4HkRXGsd6FglBINgEHsAsotPDd0d2diVfRBjBYRgOTEQzJVBLcMMIHqMhYA%3D%3D&_api_name=get_token&api_access_key=15dfa422d02d49108741f011b6a5e3f9&_api_signature=iteFyLXHfdIzy6639R%2FmZ%2FsQHfc%3D&return_url=http%3A%2F%2Fwww.ylzinfo.com&_api_version=1.0.0&_api_access_key=15dfa422d02d49108741f011b6a5e3f9";
//        String url = "http://www.baidu.com";
        driver.get(url); // 打开指定的网站

        //driver.navigate().to(url); // 打开指定的网站

        /*
         *
         * driver.findElement(By.id("kw")).sendKeys(new String[] { "hello" });//
         * 找到kw元素的id，然后输入hello driver.findElement(By.id("su")).click(); // 点击按扭
         */
        try {
            /**
             * WebDriver自带了一个智能等待的方法。 dr.manage().timeouts().implicitlyWait(arg0, arg1）；
             * Arg0：等待的时间长度，int 类型 ； Arg1：等待时间的单位 TimeUnit.SECONDS 一般用秒作为单位。
             */
            driver.manage().timeouts().implicitlyWait(1, TimeUnit.SECONDS);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //获取当前浏览器的信息
        System.out.println("Title:" + driver.getTitle());
        System.out.println("currentUrl:" + driver.getCurrentUrl());

        //执行js脚本
        String jString = "alert('122')";
        ((JavascriptExecutor) driver).executeScript(jString);

        //获取单个元素
        WebElement element = driver.findElement(By.id("wrapper"));
        System.out.println(element.getAttribute("class"));

        //获取多个元素
        List<WebElement> elList = driver.findElements(By.tagName("input"));
        for (WebElement e : elList) {
            System.out.println("获取多个元素:" + e.getAttribute("name"));
        }

        //定位层级元素
        WebElement e = driver.findElement(By.cssSelector("#qrcode-item qrcode-item-1"));
        List<WebElement> list = e.findElements(By.tagName("div"));
        for (WebElement e1 : list) {
            System.out.println("定位层级元素:" + e1.getAttribute("class"));
        }


        //获取当前的窗口
        String currentWindow = driver.getWindowHandle();

        //获取所有的窗口
        Set<String> handles = driver.getWindowHandles();

        //遍历窗口
        Iterator<String> iterator = handles.iterator();
        while (iterator.hasNext()) {
            if (currentWindow == iterator.next())
                continue;
            //跳转到弹出的窗口
            WebDriver driver2 = driver.switchTo().window(iterator.next());
            driver2.getTitle();

        }


        //处理弹出框
        Alert alert = driver.switchTo().alert();
        alert.getText();
        alert.dismiss();//相当于点击取消


        Alert confirm = driver.switchTo().alert();
        confirm.getText();
        confirm.accept();//相当于点击确认


        Alert prompt = driver.switchTo().alert();
        prompt.getText();
        prompt.accept();
        prompt.sendKeys("测试1");//输入值

        //处理下拉列表
        Select select = new Select(driver.findElement(By.id("select")));
        select.selectByIndex(1);
        select.selectByValue("西安");
        select.selectByVisibleText("咸阳");
        //获取下拉框的全部选项
        List<WebElement> list2 = select.getOptions();
        for (WebElement webElement : list2) {
            webElement.click();//点击下拉框
        }

        //处理cookie
        //添加一个cookie
        Cookie cookie = new Cookie("COOKIE", "NAME", "D://COOKIES");
        driver.manage().addCookie(cookie);
        //获取cookies
        Set<Cookie> set = driver.manage().getCookies();
        Iterator<Cookie> iterator2 = set.iterator();
        while (iterator2.hasNext()) {
            Cookie c = iterator2.next();
            c.getName();
            c.getValue();
            c.getPath();
        }

        driver.manage().deleteAllCookies();
        driver.manage().deleteCookie(cookie);
        driver.manage().deleteCookieNamed("COOKIE");


        //等待加载完页面
        try {
            driver.manage().timeouts().wait(1);
            driver.manage().timeouts().implicitlyWait(1, TimeUnit.SECONDS);//等待界面加载完
        } catch (InterruptedException e2) {

            e2.printStackTrace();
        }

        //模拟鼠标和键盘操作
        Actions action = new Actions(driver);
        action.click();
        action.dragAndDrop(element, e);
        action.sendKeys(element, "12222").perform();
        action.click(element);
//        action.keyDown(currentWindow);


        driver.quit();// 退出浏览器

        /**
         * dr.quit()和dr.close()都可以退出浏览器,简单的说一下两者的区别：第一个close，
         * 如果打开了多个页面是关不干净的，它只关闭当前的一个页面。第二个quit，
         * 是退出了所有Webdriver所有的窗口，退的非常干净，所以推荐使用quit最为一个case退出的方法。
         */
    }
}
